<?php
/**
 * @version		$Id: genm.php $
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');

/**
 * GenM model.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_gencode
 * @since		1.6
 */
class GenCodeModelGenM extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.6
	 */
	protected $text_prefix = 'COM_GENCODE_GENM';

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'GenM', $prefix = 'GenCodeTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_gencode.genm', 'genm', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}
				
		if($form->getValue('id') || (isset($data['id']) && $data['id']))
		{
			//disable select type (list or form)
			$form->setFieldAttribute('type', 'disabled', 'true');
			$form->setFieldAttribute('type', 'required', 'false');
			
			//ignore value
			$form->setFieldAttribute('type', 'filter', 'unset');
		}
		
		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_gencode.edit.genm.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		}

		return $data;
	}
	
	/**
	 * Function to get list tables from db
	 */
	public function getTables()
	{
		$db = JFactory::getDbo();
		$query = "SELECT * FROM #__gencode_gendbs WHERE component_id = " . (int) JFactory::getSession()->get('component_id', 0);
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		return $rs;
	}
	
	/**
	 * This function will select field from component tables which created in admin
	 * 
	 * @return fields (include default fields)
	 */
	public function getTableFields()
	{
		$tableId = JRequest::getInt('table_id', NULL);
		
		if(!$tableId)
			return false;
			
		$db = JFactory::getDbo();
		$query = "SELECT * FROM #__gencode_fields WHERE gendb_id = '$tableId' ORDER BY id ASC";
		
		$db->setQuery($query);
		
		$rsFields = $db->loadObjectList('name');
		
		return $rsFields;
	}
	
	function getItem()
	{
		$item = parent::getItem();
		
		$tableId = JRequest::getVar('table_id', NULL);
		$item->form_fields = $this->getFormFields($item->id, $tableId);
		
		return $item;
	}
	
	/**
	 * Function to get field from db, include tables in admin (not in db)
	 */
	public function getFields($tableId = null)
	{
		//get global config
		$config = JFactory::getConfig();
		$table = JRequest::getString('table');
		
		if(!$table)
		{
			$table = $tableId;
			
			if(!$table)
				return false;
		}
		
		$db = JFactory::getDbo();
		
		$tables = $db->getTableList();
		
		$checkTable = $config->get('dbprefix') . $table;
		
		//check if table in DB (categories, language, users, usergroups)
		if(in_array($checkTable, $tables))
		{
			$fields = $db->getTableColumns($checkTable);
		}
		else //if table not exist in db, will be exist in admin
		{
			$defaultFields = TableOptionsHelper::defaultFields();

			$query = "SELECT * FROM #__gencode_fields WHERE gendb_id = (SELECT id FROM #__gencode_gendbs WHERE name = '$table') ORDER BY id ASC";
			$db->setQuery($query);
			
			$rs = $db->loadObjectList();
			
			$id = array_shift($defaultFields);
			
			$fields['id'] = $id['type'];
			
			foreach ($rs as $field)
				$fields[$field->name] = $field->type;
				
			foreach ($defaultFields as $defaultFieldKey => $defaultFieldValue)
				$fields[$defaultFieldKey] = $defaultFieldValue['type'];
		}
		
		//var_dump($fields);
		
		return $fields;
	}
	
	/**
	 * Function to get fields for form
	 * 
	 * @param Int $genmId
	 * @param Sring $field
	 * 
	 * @return All fields and field's param in form
	 */
	public function getFormFields($genmId, $table_id = NULL, $field = NULL)
	{
		$db = JFactory::getDbo();
		$query = "SELECT * FROM #__gencode_genm_form_fields WHERE genm_id = '$genmId'";
		
		if($table_id)
			$query .= " AND table_id = '$table_id'";
		
		if($field)
			$query .= " AND field_name = '$field'";
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		return $rs;
	}
	
	public function save($data)
	{
		$post = JRequest::get('post');
		
		$saveResult = parent::save($data);
		
		if ($saveResult)
		{
			$itemId = $this->getState($this->getName().'.id');
			
			$db = JFactory::getDbo();
			
			//var_dump($post); die;
			
			$editMode = $post['edit_mode'];
			
			/* for list */
			if ($editMode == 'list')
			{
				//save fields
				$this->saveFields($itemId, $post['jform']);
				
				//save joins
				$this->saveJoins($itemId, $post['jform']);
			}
			elseif ($editMode == 'form')
			{
				
				$this->saveFormFieldsParams($itemId, $post['jform']['table_id'], $post['field']);
			}
				
		}
		
		return $saveResult;
	}
	
	/**
	 * Use to save fields params in form
	 * 
	 * @param Int $itemId Model ID
	 * @param Int $tableId Table ID
	 * @param Array $fields Array of fields
	 * 
	 * @return Boolean True / False
	 */
	protected function saveFormFieldsParams($itemId, $tableId, $fields)
	{
		$db = JFactory::getDbo();
		
		//delete all recs in db before update
		$query = "DELETE FROM #__gencode_genm_form_fields WHERE genm_id = '$itemId'";
		$db->setQuery($query);		
		$db->query();
		
		foreach ($fields as $field => $params)
		{
			
			if(is_array($params))
			{
				$type = array_shift($params);
				
				$params = serialize(str_replace("'", "\'", $params));
				
				$query = "INSERT INTO #__gencode_genm_form_fields SET 	genm_id 	= '".$itemId."',
																		table_id 	= '".$tableId."',
																		field_name 	= '".$field."',
																		field_type	= '".$type."',
																		params 		= '".$params."'
				";
				
				$db->setQuery($query);		
				$db->query();
				
				if($db->getErrorMsg())
				{
					die($query . '. Error: '. $db->getErrorMsg());
					return false;
				}
					
			}
		}
		
		return true;
	}
	
	protected function saveJoins($itemId, $post)
	{
		$db = JFactory::getDbo();
		
		//delete all recs in db before update
		$query = "DELETE FROM #__gencode_genm_join WHERE genm_id = '$itemId'";
		$db->setQuery($query);		
		$db->query();
		
		foreach ($post['join_type'] as $key => $joinType)
		{
			if($post['join_table'][$key] != '')
			{
				$query = "INSERT INTO #__gencode_genm_join SET 	genm_id 		= '".$itemId."',
																join_type 		= '".$post['join_type'][$key]."',
																join_table 		= '".$post['join_table'][$key]."',
																join_table_fields	= '".$post['join_table_fields'][$key]."',
																join_table_on_1 = '".$post['join_table_on_1'][$key]."',
																join_field_on_1 = '".$post['join_field_on_1'][$key]."',
																join_table_on_2 = '".$post['join_table_on_2'][$key]."',
																join_field_on_2 = '".$post['join_field_on_2'][$key]."'
				";
				
				$db->setQuery($query);		
				$db->query();
				
				if($db->getErrorMsg())
				{
					die($query . '. Error: '. $db->getErrorMsg());
					return false;
				}
					
			}
		}
		
		return true;
	}
	
	protected function saveFields($itemId, $post)
	{
		$fields['genm_id'] 		= $itemId;
		$fields['table_id'] 	= $post['table_id'];
		$fields['field'] 		= false;
		
		$result = $this->_save('#__gencode_genm_fields', 'genm_id', $itemId, $fields, $post);
		
		return $result;
	}
	
	protected function _save($table, $keyToDelete, $itemId, $fields, $post)
	{
		$db = JFactory::getDbo();
		
		//delete all recs in db before update
		$query = "DELETE FROM $table WHERE $keyToDelete = '$itemId'";
		$db->setQuery($query);
		
		$db->query();
		
		if($db->getErrorMsg())
		{
			die($query);
			return false;
		}
		
		//check if no field selected. set default: id
		if(!isset($post['fields']) || ($post['fields'] && empty($post['fields'])))
			$post['fields'] = array('id');
		
		if($post['table_id'])
		{
			foreach ($post['fields'] as $field)
			{
				//init variables				
				$query = null;
				$q = array();
				
				foreach ($fields as $key => $val)
				{
					if($val === false)
						$val = $field;
					
					$q[] = $key . " = '$val' ";
				}
				
				$setQuery = implode(',', $q);
				
				//insert
				$query = "INSERT INTO $table SET $setQuery";
				
				//set query
				$db->setQuery($query);
				
				//query
				$db->query();
				
				if($db->getErrorMsg())
				{
					die($query);
					return false;
				}
			}
		}
		
		return true;
	}
	
	/**
	 * This function will get all fields in #__gencode_genm_fields
	 * that model selected
	 */
	public function getGenmField()
	{
		return $this->_get('#__gencode_genm_fields', 'field', 'array');
	}
	
	/**
	 * Function to get join type from #__gencode_genm_join
	 */
	function getJoins()
	{
		return $this->_get('#__gencode_genm_join');
	}
	
	/**
	 * Function to get all model form
	 */
	function getModelForms()
	{
		$db = JFactory::getDbo();
		$genmId = JRequest::getInt('id');
		
		$query = "SELECT * FROM #__gencode_genms WHERE type = 'form' AND component_id = " . (int) JFactory::getSession()->get('component_id', 0);
		$db->setQuery($query);
		
		$rs = $db->loadObjectList();
		
		return $rs;
	}
	
	/**
	 * Function to get recs
	 */
	function _get($table, $field = null, $return = 'obj')
	{
		$db = JFactory::getDbo();
		
		$genmId = JRequest::getInt('id');
		
		if(!$field)
			$field = '*';
		
		$query = "SELECT $field FROM $table WHERE genm_id = '$genmId'";
		$db->setQuery($query);
		
		if($return == 'obj')
			$result = $db->loadObjectList();
		elseif($return == 'array')
			$result = $db->loadResultArray();
		
		if(!$db->getErrorMsg())
			return $result;
			
		return false;
	}
}
